package com.nervenets.shopping.service.impl;

import com.nervenets.general.enumeration.Action;
import com.nervenets.general.exception.LogicException;
import com.nervenets.general.service.impl.BaseServiceImpl;
import com.nervenets.general.web.params.Params;
import com.nervenets.shopping.hibernate.dao.GlobalRuleDao;
import com.nervenets.shopping.hibernate.domain.common.GlobalRule;
import com.nervenets.shopping.service.GlobalRuleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class GlobalRuleServiceImpl extends BaseServiceImpl<GlobalRule, GlobalRuleDao> implements GlobalRuleService {
    @Override
    protected void after(Action action, GlobalRule globalRule, Params... params) {
        super.after(action, globalRule, params);

        if (null == dao.findTopByEnableIsTrueAndDeletedOrderById(0)) {
            throw new LogicException("至少需要开启一个可用的全局配置");
        }

        if (count((predicates, root, query, builder) -> predicates.add(builder.isTrue(root.get("enable")))) > 1) {
            throw new LogicException("只能开启一个全局设置");
        }
    }

    @Override
    public GlobalRule getGlobalRule() {
        return dao.findTopByEnableIsTrueAndDeletedOrderById(0);
    }

    @Override
    @Transactional
    public void updateGlobalRuleToTrue(GlobalRule globalRule) {
        dao.updateAllEnableToFalse();
        dao.updateGlobalRuleEnable(globalRule.getId(), true);
    }
}
